package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.AddressClient;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequsetParams;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utlis.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    /**
     * 创建订单：实现方法
     *
     * @param requestParams
     * @return
     */

    @Autowired(required = false)
    private ItemClient itemClient;

    @Autowired(required = false)
    private IdWorker idWorker;

    @Autowired(required = false)
    private AddressClient addressClient;

    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    private OrderLogisticsMapper orderLogisticsMapper;

    //创建订单详情


    @Transactional  //开启事务
    @Override
    public Long createOrder(RequsetParams requsetParams) {

        //**商品信息
        Order order = new Order();
        //- 1）根据雪花算法生成订单id
        Long id=idWorker.nextId();
        order.setId(id);//调用工具类生成订单id

        //- 2）商品微服务提供FeignClient，实现根据id查询商品的接口
        //- 3）根据itemId查询商品信息
        Item item = itemClient.findById(requsetParams.getItemId());
        if (item==null){
            throw new RuntimeException("选购商品已下架");
        }
        if (item.getStock()<requsetParams.getNum()){
            throw new RuntimeException("选购商品超过库存数");
        }
        //- 4）基于商品价格、购买数量计算商品总价：totalFee
        Long price = item.getPrice();
        Integer num = requsetParams.getNum();
        long totalFee = price*num;
        //- 5）封装Order对象，初始status为未支付
        order.setTotalFee(totalFee);
        order.setUserId(2L);
        order.setPaymentType(requsetParams.getPaymentType());
        order.setPaymentType(order.getPaymentType());
        order.setStatus(4); //确认收货，交易成功
        //- 6）将Order写入数据库tb_order表中
        orderMapper.insert(order);


        //**订单详情
        //- 7）将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        //- 8）将user-service的根据id查询地址接口封装为FeignClient
        OrderDetail detail = new OrderDetail();
        detail.setTitle(item.getName());
        detail.setSpec(item.getSpec());
        detail.setPrice(item.getPrice());
        detail.setNum(requsetParams.getNum());
        detail.setItemId(item.getId());
        detail.setImage(item.getImage());
        detail.setOrderId(order.getId());
        orderDetailMapper.insert(detail);

        //**地址
        Long addressId = requsetParams.getAddressId();
        //- 9）根据addressId查询user-service服务，获取地址信息
        Address address = addressClient.listAddressId(addressId);
        //- 10）将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        //**要把address的属性拷贝到 orderLogistics中，看一下它们属性一不一样呢，有一些关键字段一样，可以拷贝——BeanUtils.copyProperties（从哪，到哪）
        BeanUtils.copyProperties(address,orderLogistics);
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setPhone(address.getMobile());
        orderLogisticsMapper.insert(orderLogistics);

        //**扣减库存
        //- 11）在item-service提供减库存接口，并编写FeignClient
        //- 12）调用item-service的减库存接口
        try {
            item.setSold(item.getSold()+ requsetParams.getNum());
            item.setStock(item.getStock()- requsetParams.getNum());
            itemClient.update(item);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }

        return order.getId() ;
    }
}
